package com.mspbots.rule.queue.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 * @author Dennis
 */
@Slf4j
@Component
public class TimedDeleteCache {

    public static final String REDIS_KEY_PREFIX_ESCALATION = "MSPBOTS:CONFIG:ESCALATION:*";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Scheduled(cron = "0 0 0 ? * MON")
    public void compareDate() {
        Date createDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sysDate = sdf.format(createDate);
        String imptimeBegin = null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(createDate);
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            cal.add(Calendar.DATE, -6);
            imptimeBegin = sdf.format(cal.getTime());
        } else if (cal.get(Calendar.DAY_OF_WEEK) == 2) {
            imptimeBegin = sdf.format(cal.getTime());
        } else {
            cal.add(Calendar.DATE, 2 - cal.get(Calendar.DAY_OF_WEEK));
            imptimeBegin = sdf.format(cal.getTime());
        }
        if (imptimeBegin.equals(sysDate)) {
            Set<String> keys = stringRedisTemplate.keys(REDIS_KEY_PREFIX_ESCALATION);
            if (!StringUtils.isEmpty(keys)) {
                stringRedisTemplate.delete(keys);
            }
        }
    }
}
